<?php
require "../../../../framework/bootstrap.inc.php";
require "Config.php";
require "OAuth_Client.php";
require "util.php";
require "RpcClient.php";
require "RpcService.php";
require "OrderService.php";

$shopid=$_GET["shopid"];
$date=$_GET["getdate"];
if(!$shopid)die("店铺ID不能为空");
$isseting=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_systemsetting')." order by id asc limit 1");
$app_key = $isseting["elem_key"];
$app_secret = $isseting["elem_secret"];
$sandbox = true;
$scope = "all";
$config = new Config($app_key, $app_secret, $sandbox);
$shopItem=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_elemtoken')." where groupid=:a",array(":a"=>$shopid));
$tokenItem = get_token_by_shopid($shopItem["shopid"]);
if(TIMESTAMP>$tokenItem->expires_in){
    $client=new OAuth_Client($config);
    $returnstr = $client->get_token_by_refresh_token($tokenItem->refresh_token, "all");
    $token=$returnstr->access_token;
    $data=array(
        "access_token"=>$returnstr->access_token,
        "expires_in"=>($returnstr->expires_in)+TIMESTAMP,
        "refresh_token"=>$returnstr->refresh_token,
    );
    pdo_update("j_hmoney_elemtoken",$data,array("id"=>$shopItem["id"]));
}else{
    $token=$tokenItem;
}
if ($token == null) die("获取token错误");
$order_service = new OrderService($token,$config);
$startDate="";
$endDate="";
switch($date){
    case 1:
        $startDate=$endDate=date('Y-m-d');
        break;
    case 2:
        $startDate=$endDate=date('Y-m-d',strtotime('-1 day'));
        break;
    case 3:
        $startDate=date('Y-m-d',strtotime('-6 day'));
        $endDate=date('Y-m-d');
        break;
    case 4:
        $startDate=date('Y-m')."-01";
        $tempdate=date('Y-m',strtotime('+1 month'));
        $endDate=date('Y-m-d',strtotime('-1 day',strtotime(date('Y-m',strtotime('+1 month')))));
        break;
}
$list=$order_service->get_all_orders();
switch($message["type"]){
    case 10:
        $userId = $message["userId"];


        $order = json_decode($message["message"]);
        $order_service->confirm_order($order->id);
        $isNew=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_takeoutorder')." where orderid=:a",array(":a"=>$message['orderId']));
        if($isNew)return;
        $data=array(
            "platform"=>1,
            "userId"=>$order->userId,
            "shopid"=>$order->shopId,
            "orderid"=>$order->id,
            "createtime"=>strtotime($order->createdAt),
            "activetime"=>strtotime($order->activeAt),
            "deliverFee"=>format_price($order->deliverFee),
            "description"=>$order->description,
            "mobile"=>implode(",",$order->phoneList),
            "status"=>$order->status,
            "refundStatus"=>$order->refundStatus,
            "totalPrice"=>format_price($order->totalPrice),
            "originalPrice"=>format_price($order->originalPrice),
            "realname"=>$order->consignee,
            "deliveryGeo"=>$order->deliveryGeo,
            "deliveryPoiAddress"=>$order->deliveryPoiAddress,
            "income"=>format_price($order->income),
            "serviceRate"=>format_price($order->serviceRate),
            "serviceFee"=>format_price($order->serviceFee),
            "hongbao"=>format_price($order->hongbao),
            "packageFee"=>format_price($order->packageFee),
            "activityTotal"=>format_price($order->activityTotal),
            "shopPart"=>format_price($order->shopPart),
            "elemePart"=>format_price($order->elemePart),
            "VipDeliveryFeeDiscount"=>format_price($order->vipDeliveryFeeDiscount),
            "cancelOrderDescription"=>$order->cancelOrderDescription,
            "cancelOrderCreatedAt"=>$order->cancelOrderCreatedAt,
        );
        pdo_insert("j_hmoney_takeoutorder",$data);
        $goodsbox=$order->groups;
        foreach($goodsbox as $goodslist){
            foreach($goodslist->items as $goods){
                $gooddata=array(
                    "orderid"=>$order->id,
                    "shopid"=>$message['shopId'],
                    "goodid"=>$goods->id,
                    "skuid"=>$goods->skuId,
                    "title"=>$goods->name,
                    "pcate"=>$goods->categoryId,
                    "price"=>format_price($goods->price),
                    "quantity"=>$goods->quantity,
                    "total"=>format_price($goods->total),
                    "userprice"=>format_price($goods->userPrice),
                    "shopprice"=>$goods->shopPrice,
                    "additions"=>implode(",",$goods->additions),
                    "newspecs"=>implode(",",$goods->newSpecs),
                    "attributes"=>implode(",",$goods->attributes),
                );
                pdo_insert("j_hmoney_takeoutordergoods",$gooddata);
            }
        }
        wildDog_socket($message["shopId"],$order->id);
        break;
}

/*
 {
  "{"requestId":"200008486196596798","type":10,"
message":"{"id":"3016142318666167311","orderId":"3016142318666167311","address":"东平国家森林公园三单元四楼五室","createdAt":"2017-12-03T15:04:55","activeAt":"2017-12-03T15:04:55","deliverFee":0.01,"deliverTime":null,"description":"",

"groups":[{"name":"1号篮子","type":"normal","items":[{"id":1327369753,"skuId":200000130426627134,"name":"Tset蛋面3","categoryId":1,"price":0.13,"quantity":1,"total":0.13,"additions":[],"newSpecs":[],"attributes":[],"extendCode":"","barCode":"","weight":1.0,"userPrice":0.0,"shopPrice":0.0,"vfoodId":1315186503},{"id":1327369742,"skuId":200000130426615870,"name":"Tset蛋面2","categoryId":1,"price":0.11,"quantity":1,"total":0.11,"additions":[],"newSpecs":[],"attributes":[],"extendCode":"","barCode":"","weight":1.0,"userPrice":0.0,"shopPrice":0.0,"vfoodId":1315186493}]}],

"invoice":null,"book":false,"onlinePaid":true,"railwayAddress":null,"phoneList":["13751858196"],"shopId":159253207,"shopName":"云门店收银台测试店铺","daySn":1,"status":"unprocessed","refundStatus":"noRefund","userId":568810346,"totalPrice":0.25,"originalPrice":0.25,"consignee":"吴先生 先生","deliveryGeo":"121.48234,31.67892","deliveryPoiAddress":"东平国家森林公园三单元四楼五室","invoiced":false,"income":0.25,"serviceRate":0.0,"serviceFee":-0.0,"hongbao":0.0,"packageFee":0.0,"activityTotal":-0.0,"shopPart":-0.0,"elemePart":-0.0,"downgraded":false,"vipDeliveryFeeDiscount":0.0,"openId":"","secretPhoneExpireTime":null,"orderActivities":[],"invoiceType":null,"taxpayerId":"","coldBoxFee":0.0,"cancelOrderDescription":null,"cancelOrderCreatedAt":null}",

"shopId":159253207,"userId":568810346,"timestamp":1512284815000,"orderId":"3016142318666167311"}"
}*/
